package com.isunland.managesystem.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.bugtags.library.Bugtags;
import com.google.gson.Gson;
import com.isunland.managesystem.BuildConfig;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.GridViewAdapter;
import com.isunland.managesystem.adapter.GuideCommonAdapter;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.GlideImageLoader;
import com.isunland.managesystem.common.HintResponse;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CompanyForumType;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.GuideMenu;
import com.isunland.managesystem.entity.GuideMenuNewOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.ConfigUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.utils.UpdateUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/3/14 10:05
 */
public class GuideMenuNewFragment extends Fragment {

  @BindView(R.id.ll_loading) View mLoadingView;   //加载视图

  @BindView(R.id.gv) GridView gv;
  @BindView(R.id.roll_banner) Banner banner;//轮播图片
  //将网址存入到集合中
  ArrayList<Integer> images = new ArrayList<>();
  @BindView(R.id.gv_common) GridView gvCommon;
  private View mErrorView;  //错误视图
  private BaseVolleyActivity mActivity;
  private GridViewAdapter mAdapter;
  private ArrayList<GuideMenu> mList = new ArrayList<>();
  private ArrayList<GuideMenu> mListCommon = new ArrayList<>();
  private GuideCommonAdapter mCommonAdapter;
  private CurrentUser mUser;

  @Override public void onStart() {
    mActivity = (BaseVolleyActivity) getActivity();
    volleyPostHint();// 提示
    UpdateUtil.update(this, false);//强制升级
    super.onStart();
  }

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {

    setHasOptionsMenu(true);
    mUser = CurrentUser.newInstance(getActivity());
    String name = mUser.getName();
    String password = mUser.getPassword();
    Bugtags.setUserData("name", name);
    Bugtags.setUserData("password", password);
    mActivity = (BaseVolleyActivity) getActivity();
    if (mActivity.getSupportActionBar() != null) {
      String realName = mUser.getRealName();
      String titleStr = TextUtils.isEmpty(realName) ? getString(R.string.app_name) : realName;
      if (BuildConfig.DEBUG) titleStr = "开发版: " + titleStr;
      mActivity.getSupportActionBar().setTitle(titleStr);
    }
    mList = new ArrayList<>();
    mListCommon = new ArrayList<>();
    images = getGuideData();

    super.onCreate(savedInstanceState);
  }

  private ArrayList<Integer> getGuideData() {

    ArrayList<Integer> imageList = new ArrayList<>();
    imageList.add(MyUtils.isWeiJia() ? R.drawable.wj_banner1 : R.drawable.banner1);
    imageList.add(MyUtils.isWeiJia() ? R.drawable.wj_banner2 : R.drawable.banner2);
    imageList.add(MyUtils.isWeiJia() ? R.drawable.wj_banner3 : R.drawable.banner3);
    if (MyUtils.isWeiJia()) {
      imageList.add(R.drawable.wj_banner4);
    }
    return imageList;
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_guide_new, container, false);
    ButterKnife.bind(this, view);
    gvCommon.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //跳转到二级菜单列表
        GuideMenu menu = mListCommon.get(position);
        String flag = menu.getRoleTypeFlag();
        // 更新服务端类别参数.
        BaseVolleyActivity.setRoleTypeFlag(flag);
        mUser.setRoleTypeFlag(flag);
        int code = MyStringUtil.valueOfInt(menu.getAlias(), 0);
        if (ConfigUtil.get(mActivity, code) == null) {
          ToastUtil.show(R.string.wait_apps);
          return;
        }
        ConfigUtil.startByCode(mActivity, code);
      }
    });
    //错误视图
    mErrorView = View.inflate(getActivity(), R.layout.view_error, null);
    mLoadingView.setVisibility(View.GONE);
    gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //跳转到二级菜单列表
        GuideMenu item = mList.get(i);
        startListActivity(item);
      }
    });
    //初始化grideView
    initData();
    // 图片轮播配置
    initBanner();
    // 获取菜单导航
    vollePostGetGuide();
    // 获取个人日常
    vollePostGetHeadr();
    return view;
  }

  @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    String activityName =
        SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.KEY_LAUNCH_ACTIVITY, "");
    if (MyUtils.isDevelopMode(mActivity)
        && (!MyStringUtil.isEmpty(activityName))
        && (!activityName.contains("SplashActivity") && (!activityName.contains(
        "GuideMenuNewActivity")))) {
      //自动跳转,因为activityName可能变动,增加try.catch
      try {
        Intent intent = new Intent();
        intent.setClassName(mActivity.getPackageName(), activityName);
        startActivity(intent);
        return;
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    //通过菜单选择,携带配置信息.
    int code = SharedPreferencesUtil.getInt(mActivity, SharedPreferencesUtil.KEY_LAUNCH_CODE, 0);
    if (MyUtils.isDevelopMode(mActivity) && (code != 0)) {
      ConfigUtil.startByCode(mActivity, code);
    }
  }

  private void vollePostGetHeadr() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_GUIDE_SECOND_MENU);
    HashMap<String, String> params = new HashMap<>();
    params.put("parentid", "10000056260029");
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        GuideMenuNewOriginal original = new Gson().fromJson(arg0, GuideMenuNewOriginal.class);
        if (original == null) {
          ToastUtil.show("解析数据为空，重新登录！");
        } else {
          String result = original.getResult();
          //noinspection StatementWithEmptyBody
          if (MyStringUtil.equals(SuccessMessage.FAILURE, result)) {
            //                        ToastUtil.show(original.getMessage());
          } else {
            ArrayList<GuideMenu> rows = original.getRows();
            mListCommon.clear();
            mListCommon.addAll(rows);
            mCommonAdapter = new GuideCommonAdapter(mActivity, mListCommon);
            gvCommon.setAdapter(mCommonAdapter);
            mCommonAdapter.notifyDataSetChanged();
          }
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        mLoadingView.setVisibility(View.GONE);
        mErrorView.setVisibility(View.VISIBLE);
      }
    });
  }

  private void initBanner() {
    //设置banner样式
    banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
    //设置指示器位置（当banner模式中有指示器时）
    banner.setIndicatorGravity(BannerConfig.CENTER);
    //设置自动轮播，默认为true
    banner.isAutoPlay(true);
    //设置轮播时间
    banner.setDelayTime(5000);
    //设置图片集合
    //资源文件
    banner.setImages(images);
    //设置标题集合（当banner样式有显示title时）
    //        banner.setBannerTitles(titles);
    //设置banner动画效果
    banner.setBannerAnimation(Transformer.Default);
    //设置图片加载器
    banner.setImageLoader(new GlideImageLoader());
    //设置点击事件
    banner.setOnBannerListener(new OnBannerListener() {
      @Override public void OnBannerClick(int position) {
        if (MyUtils.isWeiJia() && 3 == position) {
          //跳转到果云在线
          CompanyForumType mCompanyForumType = new CompanyForumType();
          mCompanyForumType.setName("果云在线");
          mCompanyForumType.setCustomAttrs("010301");
          Intent intent = new Intent(getActivity(), AgriculturalForumPagerActivity.class);
          intent.putExtra(AgriculturalForumListFragment.EXTRA_VALUE, mCompanyForumType);
          intent.putExtra(AgriculturalForumListFragment.EXTRA_FROM,
              AgriculturalForumListFragment.TYPE);
          startActivity(intent);
        }
      }
    });
    //banner设置方法全部调用完毕时最后调用
    banner.start();
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_set, menu);

    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_item_set:
        Intent i = new Intent(getActivity(), SettingActivity.class);
        startActivity(i);

        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void vollePostGetGuide() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_GUIDE_FIRST_MENU);
    HashMap<String, String> params = new HashMap<>();
    if (MyUtils.isNetLink(getActivity())) {

      mLoadingView.setVisibility(View.VISIBLE);
      mErrorView.setVisibility(View.GONE);
    } else {
      mLoadingView.setVisibility(View.GONE);
      mErrorView.setVisibility(View.VISIBLE);
    }
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        // dialog消失
        mLoadingView.setVisibility(View.GONE);
        mErrorView.setVisibility(View.GONE);
        GuideMenuNewOriginal original = new Gson().fromJson(arg0, GuideMenuNewOriginal.class);
        if (original == null) {
          ToastUtil.show("解析数据为空，重新登录！");
          Intent i = new Intent(getActivity(), LoginActivity.class);
          startActivity(i);
        } else {
          String result = original.getResult();
          if (MyStringUtil.equals(SuccessMessage.FAILURE, result)) {
            ToastUtil.show(original.getMessage());
          } else {
            List<GuideMenu> rows = original.getRows();

            for (int i = 0; i < rows.size(); i++) {
              GuideMenu menu = rows.get(i);
              if ("103".equalsIgnoreCase(menu.getAlias())) {
                //个人日常
                rows.remove(i);
              }
            }
            if (mList == null) {
              mList = new ArrayList<>();
            }
            mList.clear();
            mList.addAll(rows);
            mAdapter = new GridViewAdapter(getActivity(), mList);
            gv.setAdapter(mAdapter);
          }
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        mLoadingView.setVisibility(View.GONE);
        mErrorView.setVisibility(View.VISIBLE);
      }
    });
  }

  private void startListActivity(GuideMenu menu) {
    Intent second = new Intent(getActivity(), GuideSecondListActivity.class);
    second.putExtra(GuideSecondListFragmen.EXTRA_VALUE, menu);
    startActivity(second);
  }

  private void initData() {
    mAdapter = new GridViewAdapter(getActivity(), mList);
    gv.setAdapter(mAdapter);
  }

  private void volleyPostHint() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_HINT_NUMBER);
    HashMap<String, String> params = new HashMap<>();
    mActivity.volleyPost(url, params, new HintResponse(mActivity, new HintResponse.CallBack() {
      @Override public void onSuccess() {
        if (mCommonAdapter != null) mCommonAdapter.notifyDataSetChanged();
      }
    }));
  }
}
